package com.vm.myview;

import java.io.File;

import org.json.JSONObject;

import com.vm.activity.UpdateDialog;
import com.vm.commons.CurrentSetting;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.vm.commons.ProgressUtil;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.db.OperationDao;
import com.vm.model.DownInfo;
import com.vm.model.Soft;
import com.vm.model.UpgradeSoft;
import com.vm.utils.DownloadThread;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月26日 下午2:14:20]
 * @Version: [v1.0]
 * 
 */
@SuppressLint("ShowToast")
public class ProgressDown {

	RequestQueue mQueue;
	private DownloadThread downThread;
	private Handler downHandler;
	private Context mContext;
	RelativeLayout rlayout_info;
	TextView tv_softName;
	ImageView iv_softImage;
	TextView tv_softSize;
	TextView tv_old_version_number;
	TextView tv_new_version_number;
	Button btn_download;
	ProgressBar progressBar;

	View view;

	DownInfoDao dao;
	DownInfo apkInfo;
	private int fileSize = 0;
	private int nowProgressValue = 0;
	UpgradeSoft upgradeSoft;
	String apkUrl;

	public ProgressDown(Context context, View view, UpgradeSoft soft) {

		this.mContext = context;
		this.view = view;
		dao = new DownInfoDao(context);
		this.upgradeSoft = soft;
		String url = VMConst.DETAIL_URL + soft.getSoftId();

		mQueue = MyVolley.getRequestQueue();

		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
				new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {

						Soft soft2 = JsonUtils.jsonToBean(arg0, Soft.class);
						apkUrl = soft2.getApkUrl();
					}
				}, null);

		mQueue.add(jsonObjectRequest);

		initProgressBar();
	}

	/**
	 * 初始化控件
	 */
	private void init() {

		btn_download = (Button) view.findViewById(R.id.btn_update);
		btn_download.setOnClickListener(downClickListener);

		progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
		rlayout_info = (RelativeLayout) view.findViewById(R.id.rlayout_info);

	}

	public void initProgressBar() {

		init();
		File apkfile = new File(StringUtil.getSdApkUrl(upgradeSoft.getName()));
		if (apkfile.exists()) {

			// 判断APK在机器的状态,正在下载,已下载,已安装
			apkInfo = dao.query(upgradeSoft.getSoftId());
			if (apkInfo != null) {
				if (apkInfo.getCompleted() == null
						|| apkInfo.getCompleted() == 0) {

					if (apkInfo.getIsPause() == 0) {
						btn_download.setText("暂停");
					} else {
						btn_download.setText("继续");
					}
				} else {
					btn_download.setText("安装");
				}
			}

		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 100:
				if (CurrentSetting.autodelete == 1) {
					File apkfile = new File(Environment
							.getExternalStorageDirectory().getPath()
							+ "/vmclient/" + upgradeSoft.getName() + ".apk");
					if (apkfile.exists()) {
						apkfile.delete();
					}
				}
				break;
			case 500:
				if (nowProgressValue <= fileSize) {

					fileSize = msg.arg1;
					progressBar.setMax(fileSize);
					new Thread() {
						@Override
						public void run() {
							while (true) {
								progressBar.setProgress(nowProgressValue);
							}
						}
					}.start();
					// }
				} else {
					Toast toast = Toast.makeText(mContext, "当前附件已下载", 500);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}

				break;
			case 600:
				nowProgressValue = msg.arg1;
				ProgressUtil.hashMap.put(upgradeSoft.getSoftId(),
						nowProgressValue);
				break;
			case 700:
				Toast toast = Toast.makeText(mContext, "网络异常或当前附件不存在", 500);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case 800:
				Toast toast1 = Toast.makeText(mContext, "URL异常，请联系管理员", 500);
				toast1.setGravity(Gravity.CENTER, 0, 0);
				toast1.show();
				break;
			case 900:
				Toast toast2 = Toast.makeText(mContext, "暂停下载", 500);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;
			case 1000:
				Toast toast3 = Toast.makeText(mContext, "下载完成", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();
				btn_download.setText("安装");

				dao.complete(upgradeSoft.getSoftId());
				File apkfile = new File(StringUtil.getSdApkUrl(upgradeSoft
						.getName()));
				if (!apkfile.exists()) {
					return;
				}
				if (CurrentSetting.autoinstall == 1) {
					Intent i = new Intent(Intent.ACTION_VIEW);

					i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
							"application/vnd.android.package-archive");
					rlayout_info.getContext().startActivity(i);
					OperationDao op = new OperationDao();
					if (op.query(upgradeSoft.getPackageName()) == 1) {

					} else {
						op.insert(upgradeSoft.getId(),
								upgradeSoft.getPackageName());
					}
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			initProgressBar();
			if (btn_download.getText().toString().equals("安装")) {
				// 执行安装
				Toast toast3 = Toast.makeText(mContext, "正在安装", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();

				File apkfile = new File(StringUtil.getSdApkUrl(upgradeSoft
						.getName()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				rlayout_info.getContext().startActivity(i);
				OperationDao op = new OperationDao();
				if (op.query(upgradeSoft.getPackageName()) == 1) {

				} else {
					op.insert(upgradeSoft.getId(), upgradeSoft.getPackageName());
				}

			} else if (btn_download.getText().toString().equals("更新")) {
				if (CurrentSetting.onlywifi == 1) {
					ConnectivityManager connManager = (ConnectivityManager) mContext
							.getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo mWifi = connManager
							.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
					if (mWifi.isConnected()) {
						btn_download.setText("暂停");

						// 下载APK
						rlayout_info.setVisibility(View.GONE);
						progressBar.setVisibility(View.VISIBLE);

						// currentId = v.getTag().toString();
						// Log.i(TAG, currentId);
						// System.out
						// .println("<<<<" + nowProgressValue + "<<<" +
						// fileSize);
						// progressText.setText("稍等");
						// progressText.setTextColor(Color.BLACK);
						Message msg = new Message();
						// msg.arg1 = currentId;
						msg.what = 100;
						// 下载地址
						// msg.obj = VMConst.DOWN_URL + currentId + "&userId="
						// + CurrentUser.USERID;
						Soft soft = new Soft();
						soft.setApkUrl(apkUrl);
						soft.setId(upgradeSoft.getSoftId());
						soft.setName(upgradeSoft.getName());
						msg.obj = soft;

						dao.start(upgradeSoft.getSoftId());

						downThread = new DownloadThread(mContext, mainHandler);
						downThread.start();

						ProgressUtil.hashMap.put(upgradeSoft.getSoftId(),
								nowProgressValue);

						do {
							downHandler = downThread.getDownHandler();
						} while (null == downHandler);

						downHandler.sendMessage(msg);
					} else {
						final UpdateDialog dialog = new UpdateDialog(mContext,
								"温馨提示", "您在非WIFI环境下,是否下载？", "确认下载", "稍后再说", "");
						dialog.getWindow().setBackgroundDrawableResource(
								android.R.color.transparent);
						dialog.setCanceledOnTouchOutside(false);
						dialog.show();
						dialog.setClicklistener(new UpdateDialog.ClickListenerInterface() {

							@Override
							public void doConfirm() {
								// TODO Auto-generated method stub
								dialog.dismiss();
								btn_download.setText("暂停");

								// 下载APK
								rlayout_info.setVisibility(View.GONE);
								progressBar.setVisibility(View.VISIBLE);

								// currentId = v.getTag().toString();
								// Log.i(TAG, currentId);
								// System.out
								// .println("<<<<" + nowProgressValue + "<<<" +
								// fileSize);
								// progressText.setText("稍等");
								// progressText.setTextColor(Color.BLACK);
								Message msg = new Message();
								// msg.arg1 = currentId;
								msg.what = 100;
								// 下载地址
								// msg.obj = VMConst.DOWN_URL + currentId +
								// "&userId="
								// + CurrentUser.USERID;
								Soft soft = new Soft();
								soft.setApkUrl(apkUrl);
								soft.setId(upgradeSoft.getSoftId());
								soft.setName(upgradeSoft.getName());
								msg.obj = soft;

								dao.start(upgradeSoft.getSoftId());

								downThread = new DownloadThread(mContext,
										mainHandler);
								downThread.start();

								ProgressUtil.hashMap.put(
										upgradeSoft.getSoftId(),
										nowProgressValue);

								do {
									downHandler = downThread.getDownHandler();
								} while (null == downHandler);

								downHandler.sendMessage(msg);
							}

							@Override
							public void doCancel() {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});
					}
				} else {
					btn_download.setText("暂停");

					// 下载APK
					rlayout_info.setVisibility(View.GONE);
					progressBar.setVisibility(View.VISIBLE);

					// currentId = v.getTag().toString();
					// Log.i(TAG, currentId);
					// System.out
					// .println("<<<<" + nowProgressValue + "<<<" + fileSize);
					// progressText.setText("稍等");
					// progressText.setTextColor(Color.BLACK);
					Message msg = new Message();
					// msg.arg1 = currentId;
					msg.what = 100;
					// 下载地址
					// msg.obj = VMConst.DOWN_URL + currentId + "&userId="
					// + CurrentUser.USERID;
					Soft soft = new Soft();
					soft.setApkUrl(apkUrl);
					soft.setId(upgradeSoft.getSoftId());
					soft.setName(upgradeSoft.getName());
					msg.obj = soft;

					dao.start(upgradeSoft.getSoftId());

					downThread = new DownloadThread(mContext, mainHandler);
					downThread.start();

					ProgressUtil.hashMap.put(upgradeSoft.getSoftId(),
							nowProgressValue);

					do {
						downHandler = downThread.getDownHandler();
					} while (null == downHandler);

					downHandler.sendMessage(msg);
				}
			} else if (btn_download.getText().toString().equals("暂停")) {

				downThread.isPause = true;
				btn_download.setText("继续");

			} else if (btn_download.getText().toString().equals("继续")) {
				if (CurrentSetting.onlywifi == 1) {
					ConnectivityManager connManager = (ConnectivityManager) mContext
							.getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo mWifi = connManager
							.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
					if (mWifi.isConnected()) {
						// downThread.setSuspend(false);

						// 下载APK
						rlayout_info.setVisibility(View.GONE);
						progressBar.setVisibility(View.VISIBLE);

						// currentId = v.getTag().toString();
						// Log.i(TAG, currentId);
						// System.out
						// .println("<<<<" + nowProgressValue + "<<<" +
						// fileSize);
						// progressText.setText("稍等");
						// progressText.setTextColor(Color.BLACK);
						Message msg = new Message();
						// msg.arg1 = currentId;
						msg.what = 100;
						// 下载地址
						// msg.obj = VMConst.DOWN_URL + currentId + "&userId="
						// + CurrentUser.USERID;
						Soft soft = new Soft();
						soft.setApkUrl(apkUrl);
						soft.setId(upgradeSoft.getSoftId());
						soft.setName(upgradeSoft.getName());
						msg.obj = soft;

						dao.start(upgradeSoft.getSoftId());

						downThread = new DownloadThread(mContext, mainHandler);
						downThread.start();

						ProgressUtil.hashMap.put(upgradeSoft.getSoftId(),
								nowProgressValue);

						do {
							downHandler = downThread.getDownHandler();
						} while (null == downHandler);

						downHandler.sendMessage(msg);
						btn_download.setText("暂停");
					} else {
						final UpdateDialog dialog = new UpdateDialog(mContext,
								"温馨提示", "您在非WIFI环境下,是否下载？", "确认下载", "稍后再说", "");
						dialog.getWindow().setBackgroundDrawableResource(
								android.R.color.transparent);
						dialog.setCanceledOnTouchOutside(false);
						dialog.show();
						dialog.setClicklistener(new UpdateDialog.ClickListenerInterface() {

							@Override
							public void doConfirm() {
								// TODO Auto-generated method stub
								dialog.dismiss();
								// downThread.setSuspend(false);

								// 下载APK
								rlayout_info.setVisibility(View.GONE);
								progressBar.setVisibility(View.VISIBLE);

								// currentId = v.getTag().toString();
								// Log.i(TAG, currentId);
								// System.out
								// .println("<<<<" + nowProgressValue + "<<<" +
								// fileSize);
								// progressText.setText("稍等");
								// progressText.setTextColor(Color.BLACK);
								Message msg = new Message();
								// msg.arg1 = currentId;
								msg.what = 100;
								// 下载地址
								// msg.obj = VMConst.DOWN_URL + currentId +
								// "&userId="
								// + CurrentUser.USERID;
								Soft soft = new Soft();
								soft.setApkUrl(apkUrl);
								soft.setId(upgradeSoft.getSoftId());
								soft.setName(upgradeSoft.getName());
								msg.obj = soft;

								dao.start(upgradeSoft.getSoftId());

								downThread = new DownloadThread(mContext,
										mainHandler);
								downThread.start();

								ProgressUtil.hashMap.put(
										upgradeSoft.getSoftId(),
										nowProgressValue);

								do {
									downHandler = downThread.getDownHandler();
								} while (null == downHandler);

								downHandler.sendMessage(msg);
								btn_download.setText("暂停");
							}

							@Override
							public void doCancel() {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});
					}
				} else {
					// downThread.setSuspend(false);

					// 下载APK
					rlayout_info.setVisibility(View.GONE);
					progressBar.setVisibility(View.VISIBLE);

					// currentId = v.getTag().toString();
					// Log.i(TAG, currentId);
					// System.out
					// .println("<<<<" + nowProgressValue + "<<<" + fileSize);
					// progressText.setText("稍等");
					// progressText.setTextColor(Color.BLACK);
					Message msg = new Message();
					// msg.arg1 = currentId;
					msg.what = 100;
					// 下载地址
					// msg.obj = VMConst.DOWN_URL + currentId + "&userId="
					// + CurrentUser.USERID;
					Soft soft = new Soft();
					soft.setApkUrl(apkUrl);
					soft.setId(upgradeSoft.getSoftId());
					soft.setName(upgradeSoft.getName());
					msg.obj = soft;

					dao.start(upgradeSoft.getSoftId());

					downThread = new DownloadThread(mContext, mainHandler);
					downThread.start();

					ProgressUtil.hashMap.put(upgradeSoft.getSoftId(),
							nowProgressValue);

					do {
						downHandler = downThread.getDownHandler();
					} while (null == downHandler);

					downHandler.sendMessage(msg);
					btn_download.setText("暂停");
				}
			}

		}
	};

}
